package com.share.shareplatform.shareorder.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.share.shareplatform.pojo.Goods;
import com.share.shareplatform.pojo.Order;
import com.share.shareplatform.pojo.exception.LogicException;
import com.share.shareplatform.shareorder.service.OrderService;
import com.share.shareplatform.util.Result;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Service
public class PayService {
    //应用ID，您的appid，收款账号就是您的appid对应支付宝账号
    private final String APP_ID = "2016101800718057";

    //商户私钥，您的pkcs8格式私钥
    private final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDhq4WjMxued0xG2J8tUfiD1tcbQDcv3YN951jOkHmhXGELR1vdloZq9Mk0v3LOejfQMV6pGiV6INyFs6XgEpF8u+DhZZ8yu2bt9jRUIZbStbnWjm2fOeyeWAU7Sbh9cqiIcDzPUF3+qjfRFOxx5nEm2uHjilljdZo28xEzH34F8fuz3VDP5r/fMMXAUgyT1MdIrpH3pYvah7Yqqs9rCdiqKNJiIklaijYBqEUvfjyZFAsSBvAmxMb48HoSdLvPqlDCyOXvym4IA2usXulMntnWSBxoB1gc4Lzl5EIx1wbAA1iH412hvlZJba58NJxCTAgspxm+p1HPgwg74TgfmlfHAgMBAAECggEAWPTuBvkciAjqznqRtKG9XusPfDSCDKI7NSQ/A5478/mgX3vPoLe3YO4BaoOVVAM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IJvIwc+rioWBmPduFe8UHC8/OdkPLy0lNJstWdq+Y11qkA6NIHZgWSR7Lpi4t4do6bm7BcOAZ+vDt/pJB/g==";


    private final String CHARSET = "UTF-8";

    //支付宝公钥，查看地址
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAofnPuOeqT1KKcVjJ6OEM1/Q6wpCUI2GCCILziQ93Kvr6tK7UU4ADbmtDdC4T516PuUgIHX1SHiAGEWhCG+FRXGn9fwui5VYLu+X5W/eKO14ENUnrgfnz3xnyduFnZ1kJFNKwj6ATgxZFfOFuBrZs9TNsM5SYzJmZ+swk6zYMUnxWwhMMkYlaY3l0xtToTmpx3WmEp2tdeouq8z3s1p2/D1XffrB5yCHEZDP7ekh2hyaeONh3cMt5SVXilKceuBdbgV9gttDBGSpwdQn8uc4XvrYOpF5THCXYx5SZlNQ975i+rSHhB0UogolbdU+hNbW5nlNett3tM3wntsIUuR29LQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    //private final String NOTIFY_URL = "http://公网地址/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:9527/order/returnUrl";


    @Autowired
    private OrderService orderService;

    public void alipay(List<Order> list, Result result, HttpServletResponse httpResponse) throws Exception{

        //Random r=new Random();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址

        request.setReturnUrl(RETURN_URL);
        //request.setNotifyUrl(RETURN_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        StringBuilder idBuilder=new StringBuilder();
        BigDecimal decimal_total=new BigDecimal("0");
        StringBuilder nameBuilder=new StringBuilder("");
        for(Order o:list){
            decimal_total=decimal_total.add(new BigDecimal(o.getPay().toString()));
            idBuilder.append(o.getId()+"-");
            Goods goods = o.getGoods();
            if(goods==null){
                throw new LogicException("商品不存在");
            }
            nameBuilder.append(o.getGoods().getName()+"x"+o.getBuyNumber()+" ");
        }

        idBuilder.deleteCharAt(idBuilder.length()-1);

        //订单编号
        String out_trade_no = idBuilder.toString();


        //付款金额，必填
        String total_amount =decimal_total.toString();

        //订单名称，必填
        String subject =nameBuilder.toString();
        //String subject="test";

        //商品描述，可空
        String body = "尊敬的会员欢迎购买 "+subject;
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        result.put("text",form);
        /*httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();*/
    }


    public Result returnUrl(Map<String,String> params, HttpServletRequest request)
            throws IOException, AlipayApiException, LogicException {
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            String[] stringIds=out_trade_no.split("-");
            ArrayList<Long> arrayList=new ArrayList<>();
            for(String id:stringIds){
                arrayList.add(Long.parseLong(id));
            }

            if(arrayList.size()==0){
                throw new LogicException("订单不存在");
            }

            //更新订单状态
            orderService.globalUpdateAllPaymentStateByIds(arrayList);
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

        }else{
            throw new LogicException("付款失败");
        }
        return Result.getInstance(200,"付款成功");

    }
}
